<template>
     <!--面包屑-->
<div style="margin-bottom: 30px">
 <el-breadcrumb separator="/">
   <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
   <el-breadcrumb-item>
       <router-link to="/ListViolationRecord">违章记录</router-link>
   </el-breadcrumb-item>
   <el-breadcrumb-item>违章记录显示</el-breadcrumb-item>
 </el-breadcrumb></div>
    <!-- 查询 -->
     <el-form :inline="true" :model="forms" class="demo-form-inline">
            <el-form-item label="违章标题:">
      <el-input v-model="forms.ViolationTitle" placeholder="请输入违章标题" clearable style="width: 150px;"/>
    </el-form-item>
    <el-form-item label="违章日期:">
      <el-date-picker
             v-model="forms.ViolationDate"
            type="date"
           placeholder="请输入违章日期"
            value-format="YYYY-MM-DD"
       clearable style="width: 180px;"
          />
   
    </el-form-item>
           <el-form-item label="车牌号:">
      <el-input v-model="forms.LicensePlateNumber" placeholder="请输入车牌号" clearable style="width: 150px;"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getListViolationRecords">查询</el-button>
              <el-button type="primary" @click="reset()" >重置</el-button>
    </el-form-item>
  </el-form> 
  <!-- 显示列表 -->
       <el-button type="primary" @click="CreateViolationRecords">新增</el-button>
           <el-button type="danger" @click="getDelAllViolationRecords">删除</el-button>
             <el-button type="success" @click="getExport" >导出</el-button>
     <el-table :data="ListViolationRecords" border style="width: 100%" ref="multipleTableRef"  @selection-change="handleSelectionChange">
       <el-table-column type="selection"  width="55" />
        <el-table-column prop="violationTitle" label="违章标题" align="center" />
          <el-table-column prop="licensePlateNumber" label="车牌号" align="center" />
             <el-table-column prop="violationContent" label="违章内容" align="center" />
               <el-table-column prop="punishmentContent" label="处罚结果" align="center" />
                   <el-table-column prop="violators" label="违章人" align="center" />
                   <el-table-column prop="violationDate" label="违章日期" align="center" >
                     <template v-slot="scope">
<span>{{ scope.row.violationDate.replace("T"," ").substring(0,10)}}</span>
    </template>
                   </el-table-column>
                   <el-table-column prop="notes" label="备注" align="center" >
                    <template v-slot="scope">
<span v-if="scope.row.notes==''">-</span>
    </template>
                   </el-table-column>
    
 <el-table-column prop="createdDate" label="创建时间" align="center" >
                 <template v-slot="scope">
<span>{{ scope.row.createdDate.replace("T"," ").substring(0,19)}}</span>
    </template>
            </el-table-column>
                
             <el-table-column prop="date" label="操作" align="center">
  <template v-slot="scope">
    <!-- 编辑操作 -->
    <div class="table-operation">
      <el-icon class="operation-icon"><EditPen /></el-icon>
      <span class="operation-text" @click="edit(scope.row.violationRecordsId)">编辑</span>
    </div>
 
    <!-- 删除操作 -->
    <div class="table-operation" style="margin-top: 8px;">
      <el-icon class="operation-icon"><CloseBold /></el-icon>
      <span class="operation-text" @click="del(scope.row.violationRecordsId)">删除</span>
    </div>
 
    <!-- 查看操作 -->
    <div class="table-operation" style="margin-top: 8px;">
      <el-icon class="operation-icon"><CircleCheck /></el-icon>
      <span class="operation-text" @click="ed(scope.row.violationRecordsId)">查看</span>
    </div>
  </template>
  
</el-table-column>
            
  </el-table>
  <!-- 分页 -->
  <div class="demo-pagination-block">

    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[3, 6, 9, 11]"
     
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
    <!-- 查看违章信息 -->
   <div>
    <el-dialog
    v-model="dialogVisible1"
    title="违章信息"
    width="800"
  >
<el-form ref="ruleFormRef" style="max-width: 500px" :model="formm"  label-width="auto" 
        class="demo-ruleForm" status-icon>

      <el-form-item label="违章标题：" prop="violationTitle">
        <el-input v-model="formm.violationTitle" placeholder="请输入违章标题" />
      </el-form-item>

      <el-form-item label="车牌号：" prop="licensePlateNumber">
       <el-select v-model="formm.licensePlateNumber" placeholder="请选择车牌号">
        <el-option v-for="item in PlateNumber" :label="item.plateNumber" :value="item.plateNumber" />

      </el-select>
      </el-form-item>


      <el-form-item label="违章人：" prop="violators">
        <el-input v-model="formm.violators" placeholder="请输入违章人" />
      </el-form-item>
      
        <el-form-item label="违章日期:" prop="violationDate">
              <el-date-picker
             v-model="formm.violationDate"
            type="date"
           value-format="YYYY-MM-DD"
           placeholder="请输入违章日期"
            style="width: 100%"
          />
 
      </el-form-item>
        <el-form-item label="违章内容:" prop="violationContent">
        <el-input v-model="formm.violationContent" type="textarea" placeholder="请输入违章内容"/>
      </el-form-item>
        <el-form-item label="处罚结果:" prop="punishmentContent">
        <el-input v-model="formm.punishmentContent" type="textarea" placeholder="请输入处罚结果"/>
      </el-form-item>
        
      <el-form-item label="备注:" prop="notes">
        <el-input v-model="formm.notes" type="textarea" />
      </el-form-item>

</el-form>
      
    <template #footer>
      <div class="dialog-footer">
       
        <el-button type="primary" @click="dialogVisible1 = false">
          关闭
        </el-button> 
      </div>
    </template>
  </el-dialog>
   </div>
</template>
<script setup lang="ts">
//显示车牌号
const PlateNumber:any=ref([])
const showLicensePlateNumber = async () => {
    axios.get("/bread/api/Vehicles/GetVehicleShowPlateNumber").then((res) => {
        PlateNumber.value = res.data.data
    })
}
//查看信息
const dialogVisible1 = ref(false)
const formm= reactive({
    "violationRecordsId": "",
  "companyID": "",
  "user_Id": "",
  "violationTitle": "",
  "licensePlateNumber": "",
  "violators": "",
  "violationDate": "",
  "violationContent": "",
  "punishmentContent": "",
  "notes": "",
  
})
const ed = (id:number) => {
    axios.get("/carwrite/api/ViolationRecord/ViolationRecordGetBy?ViolationRecordsId=" + id).then(ter => {
      formm.violationRecordsId = ter.data.data.violationRecordsId
      formm.companyID = ter.data.data.companyID
      formm.user_Id = ter.data.data.user_Id
      formm.violationTitle = ter.data.data.violationTitle
        formm.licensePlateNumber = ter.data.data.licensePlateNumber
      formm.violators = ter.data.data.violators
      formm.violationDate = ter.data.data.violationDate
      formm.violationContent = ter.data.data.violationContent
      formm.punishmentContent = ter.data.data.punishmentContent
      formm.notes = ter.data.data.notes
    })
   dialogVisible1.value = true
}
//分页
const handleSizeChange = (val: number) => {
    page.PageSize = val
  getListViolationRecords()
}
const handleCurrentChange = (val: number) => {
    page.PageIndex = val  
  getListViolationRecords()
}
//图标
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
    Star,
    CloseBold,
    EditPen,
  CircleCheck
} from '@element-plus/icons-vue'
//多选
const multipleSelection = ref([])
const multipleSelections = ref([])//整条数据
const handleSelectionChange = (val: any) => {
  multipleSelection.value = (val.map(d => d.violationRecordsId))
    multipleSelections.value = val
   console.log(multipleSelection.value) //多选的id
  
}

//组件
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

//变量
const forms=reactive({
    ViolationTitle: "",
  ViolationDate: "",
    LicensePlateNumber:""
})
//分页
const page=reactive({
    PageIndex: 1,
    PageSize: 3,
    pageCount: 0,
    totalCount:0
})
//方法
//显示违章方法
const ListViolationRecords: any = ref([])
const getListViolationRecords = () => {
    axios.get("/carread/api/ViolationRecords/GetViolationRecordAll", {
        params: {
            ViolationTitle: forms.ViolationTitle,
        ViolationDate: forms.ViolationDate,
                 LicensePlateNumber: forms.LicensePlateNumber,
            PageIndex: page.PageIndex,
            PageSize:page.PageSize,
        }
    }).then(ter => {
        ListViolationRecords.value = ter.data.data.list
     console.log(ter.data)
        page.pageCount = ter.data.data.pageCount
        page.totalCount = ter.data.data.totalCount
      
    
    }).catch(err => {
        console.log(err);
    })
}
//重置查询条件
const reset = () => {
     forms.ViolationTitle="",
    forms.ViolationDate="",
    forms.LicensePlateNumber="",

    getListViolationRecords()
}
//导出
import * as XLSX from 'xlsx';// 导出Excel
const getExport = () => {
  // let url = '/bread/api/CargoOwners/GetExcelName?CargoOwnerName='+forms.CargoOwnerName+'&CargoOwnerPhone='+forms.CargoOwnerPhone+'&DriverLicenseDate='+forms.DriverLicenseDate+'&PageIndex='+page.PageIndex+'&PageSize='+page.PageSize
  // window.location.href = url;
    ElMessageBox.confirm("是否确认导出当前选择的数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
    .then((response) => {
        //  this.selectdata 是复选框的 数据列表
        if (multipleSelections.value.length <= 0) {
            ElMessage.warning('请选择数据！');
            return;
        }
        let tableData = [
            ['序号','违章标题','车牌号', '违章内容', '处罚结果',"违章人","违章日期","备注","创建时间"]//导出表头
        ] // 表格表头
        multipleSelections.value.forEach((item, index) => {
            let rowData= []
            //导出内容的字段
            rowData = [
                index + 1, 
                item.violationTitle,
                item.licensePlateNumber,
              item.violationContent,
                  item.punishmentContent,
                item.violators,
              item.violationDate,
              item.notes,
              item.createdDate,
             

            ]
            tableData.push(rowData)
        })
        let workSheet = XLSX.utils.aoa_to_sheet(tableData);
        let bookNew = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(bookNew, workSheet, '作品名称') // 工作簿名称
        let name = '违章记录表' + timeFormat() + '.xlsx'
        XLSX.writeFile(bookNew, name) // 保存的文件名
    })
}
const timeFormat=()=> {
        let time = new Date();
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        let date = time.getDate();
        let hours = time.getHours();
        let minutes = time.getMinutes();
        let seconds = time.getSeconds();
        return year + '-' + addZero(month) + '-' + addZero(date) + ' ' + addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds);
}
const addZero=(num:any)=> {
    return num < 10 ? '0' + num : num
}
//删除（单删）
import { ElMessage, ElMessageBox } from 'element-plus'
const del = (id:number) => {
     ElMessageBox.confirm(
    '确定要删除吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
        axios.post("/carwrite/api/ViolationRecord/DeleteViolationRecord?ViolationRecordsId="+id).then(ter => {
            if (ter.data.code>0) {
                ElMessage.success('删除成功')
            getListViolationRecords()
            }
            else {
            ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
    
    })
}
//新增违章信息跳转
const CreateViolationRecords = () => {
    router.push("/CreateViolationRecord")
}
//删除（多删）
const getDelAllViolationRecords = () => {
    if (multipleSelection.value.length == 0) { 
        ElMessage.error('请选择要删除的违章信息')
        return
    }
      ElMessageBox.confirm(
    '确定要删除吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
          .then(() => {

              axios.post("/carwrite/api/ViolationRecord/DeleteAllViolationRecord", {
            vioIds:multipleSelection.value
        }).then(ter => {
            if (ter.data.code>0) {
                ElMessage.success('删除成功')
                 getListViolationRecords()
            }
            else {
            ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
    
    })
}
//修改违章信息
const edit = (id:number) => {
    router.push({
        path: "/UpdateViolationRecord",
        query: {
            id:id
        }
    })
}

//钩子函数
onMounted(async() => {
  getListViolationRecords()
    showLicensePlateNumber()
})
</script>
<style scoped>
.table-operation {
  display: flex;
  align-items: center;
}
 
.operation-icon {
  color: blue;
  margin-right: 8px; /* 图标和文本之间间距 */
}
 
.operation-text {
  color: blue;
  cursor: pointer; /* 鼠标悬停时显示为可点击 */
}
</style>
